package controller

import (
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
	"gorm.io/gorm/clause"
	"io/ioutil"
	"mygo/app/models"
	"mygo/app/tools"
	"net/http"
	"strings"
)

type SendCtl struct {
	db *gorm.DB
}

var Send = SendCtl{}

func (ctl *SendCtl) AddEmail(c *gin.Context) {
	var err error
	ctl.db = models.Db
	var email models.EmailSend
	err = c.ShouldBind(&email)
	if err != nil {
		tools.ErrorResp(c, 500, "参数错误")
		return
	}
	err = ctl.db.Create(&email).Error
	if err != nil {
		tools.ErrorResp(c, 500, "添加失败")
		return
	}
	tools.SuccessResp(c, "添加成功", "")
}

func (ctl *SendCtl) GetEmailList(c *gin.Context) {
	var err error
	ctl.db = models.Db
	var email []models.EmailSend
	err = ctl.db.Find(&email).Error
	if err != nil {
		tools.ErrorResp(c, 500, "查询失败")
		return
	}
	tools.SuccessResp(c, "查询成功", email)
}

func (ctl *SendCtl) DelEmail(c *gin.Context) {
	var err error
	ctl.db = models.Db
	id := c.Query("id")
	err = ctl.db.Delete(&models.EmailSend{}, id).Error
	if err != nil {
		tools.ErrorResp(c, 500, "删除失败")
		return
	}
	tools.SuccessResp(c, "删除成功", "")
}

func (ctl *SendCtl) UpdateEmail(c *gin.Context) {
	var err error
	ctl.db = models.Db
	var email models.EmailSend
	err = c.ShouldBind(&email)
	if err != nil {
		tools.ErrorResp(c, 500, "参数错误")
		return
	}
	err = ctl.db.Model(&models.EmailSend{}).Where("id = ?", email.Id).Updates(&email).Error
	if err != nil {
		tools.ErrorResp(c, 500, "修改失败")
		return
	}
	tools.SuccessResp(c, "修改成功", "")
}

func (ctl *SendCtl) GetEmailById(c *gin.Context) {
	var err error
	ctl.db = models.Db
	id := c.Query("id")
	var email models.EmailSend
	err = ctl.db.Where("id = ?", id).First(&email).Error
	if err != nil {
		tools.ErrorResp(c, 500, "查询失败")
		return
	}
	tools.SuccessResp(c, "查询成功", email)
}

//fax增删改查

func (ctl *SendCtl) AddFax(c *gin.Context) {
	var err error
	ctl.db = models.Db
	var fax models.FaxSend
	err = c.ShouldBind(&fax)
	if err != nil {
		tools.ErrorResp(c, 500, "参数错误")
		return
	}
	err = ctl.db.Create(&fax).Error
	if err != nil {
		tools.ErrorResp(c, 500, "添加失败")
		return
	}
	tools.SuccessResp(c, "添加成功", "")
}

func (ctl *SendCtl) GetFaxList(c *gin.Context) {
	var err error
	ctl.db = models.Db
	var fax []models.FaxSend
	err = ctl.db.Find(&fax).Error
	if err != nil {
		tools.ErrorResp(c, 500, "查询失败")
		return
	}
	tools.SuccessResp(c, "查询成功", fax)
}

func (ctl *SendCtl) DelFax(c *gin.Context) {
	var err error
	ctl.db = models.Db
	id := c.Query("id")
	err = ctl.db.Delete(&models.FaxSend{}, id).Error
	if err != nil {
		tools.ErrorResp(c, 500, "删除失败")
		return
	}
	tools.SuccessResp(c, "删除成功", "")
}

func (ctl *SendCtl) UpdateFax(c *gin.Context) {
	var err error
	ctl.db = models.Db
	var fax models.FaxSend
	err = c.ShouldBind(&fax)
	if err != nil {
		tools.ErrorResp(c, 500, "参数错误")
		return
	}
	err = ctl.db.Model(&models.FaxSend{}).Where("id = ?", fax.Id).Updates(&fax).Error
	if err != nil {
		tools.ErrorResp(c, 500, "修改失败")
		return
	}
	tools.SuccessResp(c, "修改成功", "")
}

func (ctl *SendCtl) GetFaxById(c *gin.Context) {
	var err error
	ctl.db = models.Db
	id := c.Query("id")
	var fax models.FaxSend
	err = ctl.db.Where("id = ?", id).First(&fax).Error
	if err != nil {
		tools.ErrorResp(c, 500, "查询失败")
		return
	}
	tools.SuccessResp(c, "查询成功", fax)
}

//ftp

func (ctl *SendCtl) AddFtp(c *gin.Context) {
	var err error
	ctl.db = models.Db
	var ftp models.FtpSend
	err = c.ShouldBind(&ftp)
	if err != nil {
		tools.ErrorResp(c, 500, "参数错误")
		return
	}
	err = ctl.db.Create(&ftp).Error
	if err != nil {
		tools.ErrorResp(c, 500, "添加失败")
		return
	}
	tools.SuccessResp(c, "添加成功", "")
}

func (ctl *SendCtl) GetFtpList(c *gin.Context) {
	var err error
	ctl.db = models.Db
	var ftp []models.FtpSend
	err = ctl.db.Find(&ftp).Error
	if err != nil {
		tools.ErrorResp(c, 500, "查询失败")
		return
	}
	tools.SuccessResp(c, "查询成功", ftp)
}

func (ctl *SendCtl) DelFtp(c *gin.Context) {
	var err error
	ctl.db = models.Db
	id := c.Query("id")
	err = ctl.db.Delete(&models.FtpSend{}, id).Error
	if err != nil {
		tools.ErrorResp(c, 500, "删除失败")
		return
	}
	tools.SuccessResp(c, "删除成功", "")
}

func (ctl *SendCtl) UpdateFtp(c *gin.Context) {
	var err error
	ctl.db = models.Db
	var ftp models.FtpSend
	err = c.ShouldBind(&ftp)
	if err != nil {
		tools.ErrorResp(c, 500, "参数错误")
		return
	}
	err = ctl.db.Model(&models.FtpSend{}).Where("id = ?", ftp.Id).Updates(&ftp).Error
	if err != nil {
		tools.ErrorResp(c, 500, "修改失败")
		return
	}
	tools.SuccessResp(c, "修改成功", "")
}

func (ctl *SendCtl) GetFtpById(c *gin.Context) {
	var err error
	ctl.db = models.Db
	id := c.Query("id")
	var ftp models.FtpSend
	err = ctl.db.Where("id = ?", id).First(&ftp).Error
	if err != nil {
		tools.ErrorResp(c, 500, "查询失败")
		return
	}
	tools.SuccessResp(c, "查询成功", ftp)
}

func (ctl *SendCtl) UpdateFore(c *gin.Context) {
	var err error
	ctl.db = models.Db
	var fore models.ForeList
	c.ShouldBind(&fore)
	err = ctl.db.Transaction(func(tx *gorm.DB) error {
		if err = tx.Model(&fore).Updates(&fore).Error; err != nil {
			return err
		}
		if err = tx.Model(&fore).Association("EmailSends").Replace(fore.EmailSends); err != nil {
			return err
		}
		if err = tx.Model(&fore).Association("FaxSends").Replace(fore.FaxSends); err != nil {
			return err
		}
		if err = tx.Model(&fore).Association("FtpSends").Replace(fore.FtpSends); err != nil {
			return err
		}
		return nil
	})
	//values := map[string]interface{}{
	//	"targetEmail": fore.TargetEmail,
	//	"targetFax":   fore.TargetFax,
	//	"targetFtp":   fore.TargetFtp,
	//	"IsSendEmail": fore.IsSendEmail,
	//	"IsSendFax":   fore.IsSendFax,
	//	"IsSendFtp":   fore.IsSendFtp,
	//	"FormatEmail": fore.FormatEmail,
	//	"FormatFax":   fore.FormatFax,
	//	"FormatFtp":   fore.FormatFtp,
	//}
	//err = ctl.db.Model(&models.ForeList{}).Where("id = ?", fore.Id).Updates(values).Error
	if err != nil {
		tools.ErrorResp(c, 500, "修改失败")
		return
	}
	tools.SuccessResp(c, "修改成功", "")
}

func (ctl *SendCtl) GetSendLogList(c *gin.Context) {
	var err error
	ctl.db = models.Db
	var sendLog []models.SendLog
	err = ctl.db.Find(&sendLog).Error
	if err != nil {
		tools.ErrorResp(c, 500, "查询失败")
		return
	}
	tools.SuccessResp(c, "查询成功", sendLog)
}

// getMailConfig
func (ctl *SendCtl) GetMailConfig(c *gin.Context) {
	var err error
	ctl.db = models.Db
	var mailConfig models.MailConfig
	err = ctl.db.First(&mailConfig).Error
	if err != nil {
		tools.ErrorResp(c, 500, "查询失败")
		return
	}
	tools.SuccessResp(c, "查询成功", mailConfig)
}

// updateMailConfig
func (ctl *SendCtl) UpdateMailConfig(c *gin.Context) {
	var err error
	ctl.db = models.Db
	var mailConfig models.MailConfig
	c.ShouldBind(&mailConfig)
	fmt.Println(mailConfig)
	err = ctl.db.Model(&models.MailConfig{}).Where("id = ?", mailConfig.Id).Updates(&mailConfig).Error
	if err != nil {
		tools.ErrorResp(c, 500, "修改失败")
		return
	}
	tools.SuccessResp(c, "修改成功", "")
}

//// AddTest
//func (ctl *SendCtl) AddTest(c *gin.Context) {
//	var err error
//	ctl.db = models.Db
//	var alarm models.AlarmList
//	c.ShouldBind(&alarm)
//	err = ctl.db.Create(&alarm).Error
//	if err != nil {
//		tools.ErrorResp(c, 500, "添加失败")
//		return
//	}
//	tools.SuccessResp(c, "添加成功", "")
//}

// getAlarmList
func (ctl *SendCtl) GetAlarmList(c *gin.Context) {
	var err error
	ctl.db = models.Db
	var alarm []models.AlarmList
	//err = ctl.db.Find(&alarm).Error
	err = ctl.db.Preload(clause.Associations).Find(&alarm).Error
	if err != nil {
		tools.ErrorResp(c, 500, "查询失败")
		return
	}
	tools.SuccessResp(c, "查询成功", alarm)
}

// updateAlarm
func (ctl *SendCtl) UpdateAlarm(c *gin.Context) {
	var err error
	ctl.db = models.Db
	var alarm models.AlarmList
	c.ShouldBind(&alarm)
	err = ctl.db.Transaction(func(tx *gorm.DB) error {
		if err = tx.Model(&alarm).Updates(&alarm).Error; err != nil {
			return err
		}
		if err = tx.Model(&alarm).Association("EmailSends").Replace(alarm.EmailSends); err != nil {
			return err
		}
		if err = tx.Model(&alarm).Association("FaxSends").Replace(alarm.FaxSends); err != nil {
			return err
		}
		if err = tx.Model(&alarm).Association("FtpSends").Replace(alarm.FtpSends); err != nil {
			return err
		}
		return nil
	})
	if err != nil {
		tools.ErrorResp(c, 500, "修改失败")
		return
	}
	tools.SuccessResp(c, "修改成功", "")
}

// getAlarmConfigByType
func (ctl *SendCtl) GetAlarmConfigByType(c *gin.Context) {
	var err error
	ctl.db = models.Db
	var alarmList models.AlarmList
	currentAlarm := c.Query("currentAlarm")
	currentPub := c.Query("currentPub")
	currentGrade := c.Query("currentGrade")
	region := c.Query("region")
	err = ctl.db.Preload(clause.Associations).Where("name LIKE ? AND name LIKE ? AND name LIKE ? AND region = ?", "%"+currentAlarm+"%", "%"+currentPub+"%", "%"+currentGrade+"%", region).Find(&alarmList).Error
	if err != nil {
		tools.ErrorResp(c, 500, "查询失败")
		return
	}
	tools.SuccessResp(c, "查询成功", alarmList)
	//if err == nil {
	//	emailId := strings.Split(alarmList.TargetEmail, ",")
	//	faxId := strings.Split(alarmList.TargetFax, ",")
	//	ftpId := strings.Split(alarmList.TargetFtp, ",")
	//	var emailList []models.EmailSend
	//	var faxList []models.FaxSend
	//	var ftpList []models.FtpSend
	//	var email []models.EmailSend
	//	var fax []models.FaxSend
	//	var ftp []models.FtpSend
	//	for _, v := range emailId {
	//		err = ctl.db.Where("id = ?", v).Find(&emailList).Error
	//		if err != nil {
	//			tools.ErrorResp(c, 500, "查询失败")
	//			return
	//		}
	//		email = append(email, emailList...)
	//	}
	//	for _, v := range faxId {
	//		err = ctl.db.Where("id = ?", v).Find(&faxList).Error
	//		if err != nil {
	//			tools.ErrorResp(c, 500, "查询失败")
	//			return
	//		}
	//		fax = append(fax, faxList...)
	//	}
	//	for _, v := range ftpId {
	//		err = ctl.db.Where("id = ?", v).Find(&ftpList).Error
	//		if err != nil {
	//			tools.ErrorResp(c, 500, "查询失败")
	//			return
	//		}
	//		ftp = append(ftp, ftpList...)
	//	}
	//
	//	c.JSON(200, gin.H{
	//		"code": 200,
	//		"msg":  "查询成功",
	//		"data": gin.H{
	//			"email": email,
	//			"fax":   fax,
	//			"ftp":   ftp,
	//		},
	//	})
	//	return
	//}
	//tools.ErrorResp(c, 500, "查询失败")
}

// getMessageList
func (ctl *SendCtl) GetMessageList(c *gin.Context) {
	var err error
	ctl.db = models.Db
	var messageList []models.MessageSend
	err = ctl.db.Find(&messageList).Error
	if err != nil {
		tools.ErrorResp(c, 500, "查询失败")
		return
	}
	tools.SuccessResp(c, "查询成功", messageList)
}

// sendMessage
func (ctl *SendCtl) SendMessage(c *gin.Context) {
	//	MessageUser
	ctl.db = models.Db
	var messageUser models.MessageUser
	_ = c.ShouldBind(&messageUser)
	postData := map[string]interface{}{
		"userCode": messageUser.UserCode,
		"password": messageUser.Password,
		"unixtick": messageUser.Unixtick,
	}

	//	发送post请求 http://115.239.137.23:9501/ws2/wsltfTask/getToken
	resp, err1 := http.Post("http://115.239.137.23:9501/ws2/wsltfTask/getToken", "application/json", strings.NewReader(tools.JsonEncode(postData)))

	if err1 != nil {
		fmt.Println(err1)
		return
	}
	defer resp.Body.Close()
	//	读取响应内容
	body, err2 := ioutil.ReadAll(resp.Body)
	if err2 != nil {
		fmt.Println(err2)
		return
	}
	//fmt.Println(string(body))
	//TokenRes
	var tokenRes models.TokenRes
	json.Unmarshal(body, &tokenRes)
	//MessageSendReq
	var messageSendReq models.MessageSendReq
	messageSendReq.Token = tokenRes.Result.Token
	phoneArr := strings.Split(messageUser.Phone, ",")
	for _, v := range phoneArr {
		messageSendReq.Details = append(messageSendReq.Details, models.Details{ReceiveNumber: v, TransactionId: ""})
	}
	messageSendReq.IsSame = true
	messageSendReq.SameContent = "【温州海洋预报台】您选购了2件，单价为100元，总价格为200元，验证码为12345，不要将验证码告诉别人。"

	//http://115.239.137.23:9501/ws2/wsltfTask/submitSmsTask
	resp1, err3 := http.Post("http://115.239.137.23:9501/ws2/wsltfTask/submitSmsTask", "application/json", strings.NewReader(tools.JsonEncode(messageSendReq)))
	if err3 != nil {
		fmt.Println(err3)
		return
	}
	defer resp1.Body.Close()
	//	读取响应内容
	body1, err4 := ioutil.ReadAll(resp1.Body)
	if err4 != nil {
		fmt.Println(err4)
		return
	}
	fmt.Println(string(body1))

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": gin.H{
			"req": messageSendReq,
			"res": string(body1),
		},
	})
}

//JsonEncode
